<?php
include_once('Constants.php');

class SQLBuilder {
	var $type = TYPE_SELECT;  // 语句类型
	var $tableName = null;  // 表名
	var $whereStr = null;  // where条件
	var $valueArr = array();  // where条件

	function select($tableName) {
		$this->type = TYPE_SELECT;
		$this->tableName = $tableName;
		return $this;
	}

	function insert($tableName) {
		$this->type = TYPE_INSERT;
		$this->tableName = $tableName;
		return $this;
	}

	function update($tableName) {
		$this->type = TYPE_UPDATE;
		$this->tableName = $tableName;
		return $this;
	}

	function delete($tableName) {
		$this->type = TYPE_DELETE;
		$this->tableName = $tableName;
		return $this;
	}

	function where($whereStr) {
		$this->whereStr = $whereStr;
		return $this;
	}

	function addValue($key, $value) {
		$this->valueArr[$key] = $value;
		return $this;
	}

    function build() {
		if ($this->tableName == null || $this->tableName == "") {
			return "";
		}
		$sqlStr = "";
		switch ($this->type) {
			case TYPE_INSERT:
				$sqlStr .= "insert into $this->tableName";
				$i = 0;
				$valueCount = count($this->valueArr);
				$keys = "";
				$values = "";
				foreach ($this->valueArr as $key => $value) {
					$keys .= $key;
					$values .= "'$value'";
					if ($i++ < $valueCount - 1) {
						$keys .= ",";
						$values .= ",";
					}
				}
				$sqlStr .= "(" . $keys . ") values(" . $values . ")";

				break;
			case TYPE_UPDATE:
				$sqlStr .= "update $this->tableName set ";
                $i = 0;
                $valueCount = count($this->valueArr);
                foreach ($this->valueArr as $key => $value) {
                    $sqlStr .= "$key='$value'";
                    if ($i++ < $valueCount - 1) {
                        $sqlStr .= ",";
                    }
                }
				break;
			case TYPE_DELETE:
				$sqlStr .= "delete from $this->tableName";
				break;
			default:
				$sqlStr .= "select * from $this->tableName";
				break;
		}
		if ($this->whereStr != null && $this->whereStr != '') {
			$sqlStr .= " where " . $this->whereStr;
		}
		return $sqlStr;
	}
}
?>